package com.xiaogao.serviceEdu.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaogao.centerEdu.entity.UcenterMember;
import com.xiaogao.commonUtils.JwtUtils;
import com.xiaogao.commonUtils.Result;
import com.xiaogao.serviceEdu.client.UcenterClient;
import com.xiaogao.serviceEdu.entity.EduComment;
import com.xiaogao.serviceEdu.service.EduCommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 小高
 * @createtime 2021-07-01-20:37
 * @description
 */
@RestController
@RequestMapping("/serviceEdu/comment")
@Api(description = "前端评论功能")
public class CommentFrontController {

    @Autowired
    private EduCommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    // 根据课程id查询分页评论列表
    @ApiOperation(value = "分页评论列表")
    @GetMapping("/getPageInfo/{page}/{limit}")
    public Result getPageInfo(
            @PathVariable("page")Long page,
            @PathVariable("limit")Long limit,
            String courseId){
        Page<EduComment> pageParam = new Page<>(page,limit);

        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);

        commentService.page(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();

        Map<String,Object> map = new HashMap<>();
        map.put("items",commentList);
        map.put("current",pageParam.getCurrent());
        map.put("pages",pageParam.getPages());
        map.put("size",pageParam.getSize());
        map.put("total",pageParam.getTotal());
        map.put("hasNext",pageParam.hasNext());
        map.put("hasPrevious",pageParam.hasPrevious());

        return Result.ok().data(map);
    }

    // 根据token字符串获取用户信息
    @ApiOperation(value = "添加评论")
    @PostMapping("/save")
    public Result save(@RequestBody EduComment eduComment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            return Result.error().code(28004).message("请先登录");
        }
        eduComment.setMemberId(memberId);

        UcenterMember member = ucenterClient.getInfo(memberId);

        eduComment.setNickname(member.getNickname());
        eduComment.setAvatar(member.getAvatar());

        commentService.save(eduComment);
        return Result.ok();
    }

}
